package com.jrapider.manager.data.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jrapider.manager.data.om.SysMenu;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public interface SysMenuMapper extends BaseMapper<SysMenu> {
    @Select(" SELECT " +
            "    t1.*" +
            " FROM" +
            "    sys_menu t1" +
            "        INNER JOIN" +
            "    sys_menu_role t2 ON t1.id = t2.menu_id" +
            " WHERE" +
            "    t2.role_id = #{roleId}" +
            "    AND t1.title like #{title}" +
            " order by sortcode asc ")
    List<SysMenu> queryMenuWithRole(IPage<SysMenu> page, @Param("title") String title, @Param("roleId") Long roleId);

    @Select(" SELECT " +
            "    t.*" +
            " FROM" +
            "    sys_menu t" +
            " WHERE" +
            "    t.id NOT IN (SELECT " +
            "            t1.id" +
            "        FROM" +
            "            sys_menu t1" +
            "                LEFT JOIN" +
            "            sys_menu_role t2 ON t1.id = t2.menu_id" +
            "        WHERE" +
            "            t2.role_id = #{roleId})" +
            "        AND t.title like #{title}" +
            " order by sortcode asc ")
    List<SysMenu> queryMenuWithNoRole(IPage<SysMenu> page, @Param("title") String title, @Param("roleId") Long roleId);

    @Select("select count(1) from sys_menu_role where menu_id = #{menuId} and role_id = #{roleId}")
    Long existRole(@Param("menuId") Long menuId, @Param("roleId") Long roleId);

    @Delete("delete from sys_menu_role where role_id = #{roleId} and menu_id=#{menuId}")
    void deleteMenuRelation(@Param("roleId") Long roleId, @Param("menuId") Long menuId);

    @Insert("<script>" +
            " insert into sys_menu_role(menu_id,role_id) " +
            " values " +
            " <foreach item='menuId' index='index' collection='menuIds' separator=','>" +
            "    (#{menuId},#{roleId})" +
            " </foreach>" +
            "</script>")
    void insertMenuRelation(@Param("roleId") Long roleId, @Param("menuIds") Long[] menuIds);

    @Select(" <script>" +
            " select * from sys_menu " +
            " <where>" +
            " <choose>" +
            "   <when test='pid!=null'>" +
            "       pid = #{pid}" +
            "   </when>" +
            "   <otherwise>" +
            "       pid is null" +
            "   </otherwise>" +
            " </choose>" +
            " </where>" +
            " order by sort" +
            " </script>")
    List<SysMenu> selectChild(@Param("pid") Long pid);
}
